//
//  CYSignUpViewController.m
//  cyjf
//
//  Created by tauCross on 2017/5/3.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYSignUpViewController.h"

#import "CYDataAPIRegisterModel.h"

#import "CYWebViewController.h"
#import "CYSudokuSignInOpenViewController.h"
#import "CYNavigationController.h"

#import "CYSMSExpireManager.h"



@interface CYSignUpViewController ()

@property(nonatomic, strong)UITextField *phoneTextField;
@property(nonatomic, strong)UIView *phoneLine;
@property(nonatomic, strong)UITextField *smsTextField;
@property(nonatomic, strong)UIButton *smsButton;
@property(nonatomic, strong)UIView *smsLine;
@property(nonatomic, strong)UITextField *passwordTextField;
@property(nonatomic, strong)UIView *passwordLine;
@property(nonatomic, strong)UIButton *signUpButton;
@property(nonatomic, strong)UIButton *agreementButton;

@end


@implementation CYSignUpViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self checkSMSSeconds];
}

- (void)loadUI
{
    self.navigationItem.title = @"注册";
    
    self.contentView.backgroundColor = HEXCOLOR(@"FFFFFF");

    self.tableView.hidden = YES;
    
    self.phoneLine = [UIView cy_logInLine];
    [self.contentView addSubview:self.phoneLine];
    
    self.smsLine = [UIView cy_logInLine];
    [self.contentView addSubview:self.smsLine];
    
    self.passwordLine = [UIView cy_logInLine];
    [self.contentView addSubview:self.passwordLine];
    
    self.phoneTextField = [UITextField cy_logInTextFieldWithPlaceholder:@"手机号"];
    self.phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.contentView addSubview:self.phoneTextField];
    
    self.smsTextField = [UITextField cy_logInTextFieldWithPlaceholder:@"短信验证码"];
    self.smsTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.contentView addSubview:self.smsTextField];
    
    self.passwordTextField = [UITextField cy_logInTextFieldWithPlaceholder:@"8~14位登录密码"];
    self.passwordTextField.secureTextEntry = YES;
    self.passwordTextField.returnKeyType = UIReturnKeyJoin;
    [self.contentView addSubview:self.passwordTextField];
    
    [self.passwordTextField addTarget:self action:@selector(onPasswordTextFieldEditingDidEndOnExit) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    self.signUpButton = [UIButton cy_mainButtonWithTitle:@"立即注册"];
    [self.signUpButton addTarget:self action:@selector(onSignUpButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.signUpButton];
    
    self.agreementButton = [UIButton cy_hintButtonWithDesc:@"注册即代表同意" content:@"《车蚁金服投资用户协议》" fontSize:12];
    [self.agreementButton addTarget:self action:@selector(onAgreementButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.agreementButton];
    
    self.smsButton = [[UIButton alloc] init];
    self.smsButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.smsButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.smsButton setTitleColor:APP_DEFAULT_COLOR_BLUE forState:UIControlStateNormal];
    [self.smsButton setTitleColor:HEXCOLORA(@"3E8CE6", 0.6) forState:UIControlStateHighlighted];
    [self.smsButton setTitleColor:HEXCOLOR(@"CCCCCC") forState:UIControlStateDisabled];
    self.smsButton.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
    [self.smsButton addTarget:self action:@selector(onSMSButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.smsButton];
}

- (void)layoutUI
{
    self.phoneLine.height = 1 / SCREEN_SCALE;
    self.phoneLine.width = self.contentView.width - 80;
    self.phoneLine.centerX = self.contentView.width / 2;
    self.phoneLine.bottom = 58;
    
    self.smsLine.height = 1 / SCREEN_SCALE;
    self.smsLine.width = self.contentView.width - 80;
    self.smsLine.centerX = self.contentView.width / 2;
    self.smsLine.bottom = 58 * 2;

    self.passwordLine.height = 1 / SCREEN_SCALE;
    self.passwordLine.width = self.contentView.width - 80;
    self.passwordLine.centerX = self.contentView.width / 2;
    self.passwordLine.bottom = 58 * 3;
    
    self.phoneTextField.width = self.phoneLine.width;
    self.phoneTextField.height = 35;
    self.phoneTextField.centerX = self.contentView.width / 2;
    self.phoneTextField.bottom = self.phoneLine.bottom;
    
    self.smsTextField.width = self.smsLine.width - 100;
    self.smsTextField.height = 35;
    self.smsTextField.left = self.smsLine.left;
    self.smsTextField.bottom = self.smsLine.bottom;

    self.passwordTextField.width = self.passwordLine.width;
    self.passwordTextField.height = 35;
    self.passwordTextField.centerX = self.contentView.width / 2;
    self.passwordTextField.bottom = self.passwordLine.bottom;
    
    self.signUpButton.width = self.contentView.width - 80;
    self.signUpButton.height = 44;
    self.signUpButton.centerX = self.contentView.width / 2;
    self.signUpButton.top = self.passwordTextField.bottom + 40;
    
    [self.agreementButton sizeToFit];
    self.agreementButton.height = 44;
    self.agreementButton.left = self.signUpButton.left;
    self.agreementButton.top = self.signUpButton.bottom - 4;
    
    self.smsButton.width = 100;
    self.smsButton.height = 44;
    self.smsButton.right = self.smsLine.right;
    self.smsButton.centerY = self.smsTextField.centerY;
}

#pragma mark - Actions
- (void)sendSMSAction
{
    NSString *mobile = self.phoneTextField.text;
    if(![mobile cy_isPhoneNumber])
    {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码"];
        [self.phoneTextField becomeFirstResponder];
        return;
    }
    [SVProgressHUD show];
    @weakify(self);
    [CYStandardDataAPI user_getSmsCodeWithMobile:mobile sms_type:CYDataAPISMSCodeTypeSignUp complete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            [SVProgressHUD dismiss];
            [self.smsTextField becomeFirstResponder];
            NSNumber *seconds = response.content[@"seconds"];
            if(![seconds isKindOfClass:[NSNumber class]])
            {
                seconds = @60;
            }
            [CYStandardSMSExpireManager resetExpireDate:[NSDate dateWithTimeIntervalSinceNow:seconds.doubleValue] type:CYSMSExpireTypeSignUp];
            [self checkSMSSeconds];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:response.message];
        }
    }];
}

- (void)submitAction
{
    [self.view endEditing:YES];
    NSString *mobile = self.phoneTextField.text;
    NSString *mobile_auth_code = self.smsTextField.text;
    NSString *password = self.passwordTextField.text;
    if(![mobile cy_isPhoneNumber])
    {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码"];
        [self.phoneTextField becomeFirstResponder];
        return;
    }
    if(mobile_auth_code.length == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
        [self.smsTextField becomeFirstResponder];
        return;
    }
    if(mobile_auth_code.length != 6)
    {
        [SVProgressHUD showErrorWithStatus:@"输入验证码错误"];
        [self.smsTextField becomeFirstResponder];
        return;
    }
    if(password.length < 8 || password.length > 14)
    {
        [SVProgressHUD showErrorWithStatus:@"密码长度8~14位"];
        [self.passwordTextField becomeFirstResponder];
        return;
    }
    [SVProgressHUD show];
    @weakify(self);
    [CYStandardDataAPI user_registerWithMobile:mobile mobile_auth_code:mobile_auth_code password:password complete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            CYDataAPIRegisterModel *model = [CYDataAPIRegisterModel mj_objectWithKeyValues:response.content];
            CYAuth *auth = [[CYAuth alloc] init];
            auth.token = model.token;
            auth.mobile = model.mobile;
            CYStandardAuthManager.currentAuth = auth;
            [CYStandardAuthManager saveAuth];
            [SVProgressHUD dismiss];
            CYSudokuSignInOpenViewController *sudokuSignInOpenViewController = [[CYSudokuSignInOpenViewController alloc] init];
            [self.navigationController dismissViewControllerAnimated:NO completion:nil];
            [[UIApplication sharedApplication] delegate].window.rootViewController = [[CYNavigationController alloc] initWithRootViewController:sudokuSignInOpenViewController];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:response.message];
        }
    }];
}

#pragma mark - Control Events
- (void)onSignUpButtonTouchUpInside
{
    [MobClick event:UM_EVENT_0008];
    [self submitAction];
}

- (void)onAgreementButtonTouchUpInside
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/register_service.html"];
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (void)onSMSButtonTouchUpInside
{
    [MobClick event:UM_EVENT_0007];
    [self sendSMSAction];
}

- (void)onPasswordTextFieldEditingDidEndOnExit
{
    [MobClick event:UM_EVENT_0008];
    [self submitAction];
}

#pragma mark - Private Method
- (void)checkSMSSeconds
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(checkSMSSeconds) object:nil];
    NSTimeInterval seconds = [CYStandardSMSExpireManager secondsWithType:CYSMSExpireTypeSignUp];
    if(seconds <= 0)
    {
        self.smsButton.enabled = YES;
    }
    else
    {
        self.smsButton.enabled = NO;
        [self.smsButton setTitle:[NSString stringWithFormat:@"%.0fs后重新获取", seconds] forState:UIControlStateDisabled];
        [self performSelector:@selector(checkSMSSeconds) withObject:nil afterDelay:1];
    }
}

@end
